package cn.walmt.controller;

/*
 * 动态相关功能
 */

import cn.walmt.dto.CommentDetail;
import cn.walmt.dto.PostWithUser;
import cn.walmt.dto.PostDetail;
import cn.walmt.dto.PostSummary;
import cn.walmt.entity.Post;
import cn.walmt.entity.User;
import cn.walmt.entity.Vote;
import cn.walmt.mapper.CommentMapper;
import cn.walmt.mapper.PostMapper;
import cn.walmt.mapper.UserMapper;
import cn.walmt.mapper.VoteMapper;
import cn.walmt.service.PostService;
import cn.walmt.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import util.DistanceUtil;
import util.GsonUtil;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping(value = "/post")
public class PostController {

    @Autowired
    private PostService postService;

    @Autowired
    private CommentMapper commentMapper;

    @Autowired
    private PostMapper postMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private VoteMapper voteMapper;


    @Autowired
    private UserService userService;

    private SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");

    /*
     * Q晒单，根据位置和分页号返回10条动态
     */
    @ResponseBody
    @RequestMapping(value = "/getFriendPosts", method = RequestMethod.GET)
    public String getFriendPosts(Double longitude, Double latitude, Integer pageId, HttpSession session) {
        User user = (User)session.getAttribute("user");
        List<PostWithUser> posts = postService.getFriendPosts(user.getId(), pageId);
        if (posts != null && posts.size() != 0) {
            for(PostWithUser post: posts) {
                post.setDistance(DistanceUtil.calculateDistance(longitude, latitude, post.getLongitude(), post.getLatitude()));
            }
        }
        return GsonUtil.getSuccessJson(posts);
    }


    /*
     * TODO not finished yet
     */
    @ResponseBody
    @RequestMapping(value = "/getPostsAround", method = RequestMethod.GET)
    public String getPostsAround(Double longitude, Double latitude, Integer pageId) {
        List<PostWithUser> posts = postService.getPostsAround(longitude, latitude, pageId);
        return GsonUtil.getSuccessJson(posts);
    }

    @ResponseBody
    @RequestMapping(value = "/getMyPosts", method = RequestMethod.GET)
    public String getMyPosts(HttpSession session) {
        User user = (User)session.getAttribute("user");
        List<Post> posts = postService.getPostsByUserId(user.getId());
        PostSummary summary = new PostSummary(user, posts);
        return GsonUtil.getSuccessJson(summary);
    }

    @ResponseBody
    @RequestMapping(value = "/getPostsByUser", method = RequestMethod.GET)
    public String getPostsById(Integer id) {
        User user = userService.selectUserByUserId(id);
        List<Post> posts = postService.getPostsByUserId(id);
        PostSummary summary = new PostSummary(user, posts);
        return GsonUtil.getSuccessJson(summary);
    }

    @ResponseBody
    @RequestMapping(value = "/getPostDetails", method = RequestMethod.GET)
    public String getPostDetails(Integer id, Double longitude, Double latitude, HttpSession session) {
        PostWithUser post = postService.getById(id);
        Integer distance = DistanceUtil.calculateDistance(longitude, latitude, post.getLongitude(), post.getLatitude());
        List<CommentDetail> comments = commentMapper.getComments(id);

        Post post1 = postMapper.selectByPrimaryKey(id);
        User user = userMapper.selectByPrimaryKey(post1.getUserId());
        User user1 = (User) session.getAttribute("user");
        Vote vote = new Vote();
        vote.setPostId(id);
        vote.setUserId(user1.getId());
        vote.setValid(true);
        Vote vote1 = voteMapper.isVote(vote);
        boolean isVote = (vote1 != null);

        PostDetail detail = new PostDetail(post1, user, comments, distance.toString(), isVote);
        return GsonUtil.getSuccessJson(detail);
    }

    @ResponseBody
    @RequestMapping(value = "/getImgLabel", method = RequestMethod.POST)
    public String getImgLabel(MultipartFile img, HttpSession session) {
        return postService.getImgLabel(img, session);
    }

    @ResponseBody
    @RequestMapping(value = "/releasePost", method = RequestMethod.POST)
    public String releasePost(String store, Long cost, MultipartFile img, String content, String imgLabel,
                              String position, Double longitude, Double latitude, String district, HttpSession session) {
        User user = (User) session.getAttribute("user");
        Post post = new Post();
        Date releaseTime = new Date();
        try {
            String imgName = user.getId() + "-" + sdf.format(releaseTime) + ".jpg";
            String imgPath = session.getServletContext().getRealPath("/WEB-INF/") + "upload/" + imgName;
            img.transferTo(new File(imgPath));
            String serverAddrPrefix = "http://111.230.93.13/mybatis/upload/";
            post.setImgUrl(serverAddrPrefix + imgName);
            System.out.println(imgPath);
        }catch(IOException e) {
            e.printStackTrace();
            return GsonUtil.getErrorJson(e);
        }
        post.setUserId(user.getId());
        post.setStore(store);
        post.setCost(cost);
        post.setContent(content);
        post.setImgLabel(imgLabel);
        post.setPosition(position);
        post.setLongitude(longitude);
        post.setLatitude(latitude);
        post.setDistrict(district);
        post.setReleaseTime(releaseTime);
        postService.addPost(post);

        return GsonUtil.getSuccessJson();
    }

    @ResponseBody
    @RequestMapping(value = "/getPostsByStore", method = RequestMethod.GET)
    public String getPostsByStore(String store) {
        List<PostWithUser> posts = postService.getPostsByStore(store);
        return GsonUtil.getSuccessJson(posts);
    }

}
